package com.qk.exception;

import com.qk.commom.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.View;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private final View error;

    public GlobalExceptionHandler(View error) {
        this.error = error;
    }

    /**
     * 捕获 DuplicateKeyException 异常
     */
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        String errMsg = e.getMessage();
        if(errMsg.contains("Duplicate entry")){
            String msg = errMsg.substring(errMsg.indexOf("Duplicate entry"));
            String[] arr = msg.split(" ");
            return Result.error(arr[2] + " 已存在");
        }
        return Result.error("对不起, 服务端异常, 请稍后重试 !!");
    }

    @ExceptionHandler
    public Result handleServiceException(ServiceException e){
        log.info("程序运行错误",e);
        return Result.error(e.getMessage());
    }
}
